<?php
/**
 * MatchDart! is a darts event ranking table component for joomla
 * 
 * @version		2.0.1 | $Id: matches.php 116 2009-10-12 14:08:54Z mwi.nor $
 * @package		MatchDart!
 * @subpackage	Admin
 * @copyright	Copyright (C) 2005 - 2009 Marco Wilde. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * @author		Marco Wilde, <mailto://info@matchdart.de>
 * @link		http://www.matchdart.de
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );

class MatchdartModelMatches extends JModel
{
    protected $_data;
    protected $_total;
    protected $_pagination;
    protected $_dateformat;
    protected $_eventselect;
    protected $_seasonselect;
    protected $_venueselect;
    protected $_dateselect;
    protected $_homeplayers;
    protected $_awayplayers;
    protected $_hometeams;
    protected $_awayteams;

    public function __construct()
    {
        parent::__construct();

        $app = &JFactory::getApplication();

        $config = JFactory::getConfig();
    	$db    = &JFactory::getDBO();
        
        // set defaults
		$params = &JComponentHelper::getParams( 'com_matchdart' );
		$this->_dateformat = $params->get('md_printdate');
		
        // Get the pagination request variables
        $limit		= $app->getUserStateFromRequest( 'matchdart.matches.limit', 'limit', $app->getCfg('list_limit'), 'int' );
        $limitstart	= $app->getUserStateFromRequest( 'matchdart.matches.limitstart', 'limitstart', 0, 'int' );

        // In case limit has been changed, adjust limitstart accordingly
        $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);

        $this->setState('matchdart.matches.limit', $limit);
        $this->setState('matchdart.matches.limitstart', $limitstart);	}

    protected function _buildQuery()
    {
		//TODO: Move this section to constructor like limitstart
    	$app = &JFactory::getApplication();
    	$db    = &JFactory::getDBO();

		$context			= 'com_matchdart.matches.list.';
		$showevent		= $app->getUserStateFromRequest( $context.'$eventselect',		'eventselect',		'0',	'cmd' );
		$showseason		= $app->getUserStateFromRequest( $context.'$seasonselect',	'seasonselect',		'0',	'cmd' );
		$showvenue		= $app->getUserStateFromRequest( $context.'$venueselect',		'venueselect',		'0',	'cmd' );
		$showdate		= $app->getUserStateFromRequest( $context.'$dateselect',		'dateselect',		'0',	'cmd' );
		// end section to move
		
    	$selectevent = ($showevent == 0) ? '%' : $showevent;
    	$selectseason = ($showseason == 0) ? '%' : $showseason;
    	$selectvenue = ($showvenue == 0) ? '%' : $showvenue;
    	$selectdate = ($showdate == 0) ? '%' : $showdate;
    	
    	$query = 'SELECT'.
						' M.*,'.
						' V.VenueName as MatchVenueName,'.
						' HP.PlayerName as MatchHomePlayerName,'.
						' HT.TeamName as MatchHomeTeamName,'.
						' AP.PlayerName as MatchAwayPlayerName,'.
						' AT.TeamName as MatchAwayTeamName,'.
						' E.EventUseSets,'.
						' E.EventUseTeams'.
					' FROM'.
						' #__md_matches M'.
						' LEFT JOIN #__md_venues V on (V.VenueID = M.MatchVenueID)'.
						' LEFT JOIN #__md_players HP on (HP.PlayerID = M.MatchHomePlayerID)'. 
						' LEFT JOIN #__md_teams HT on (HT.TeamID = M.MatchHomeTeamID)'. 
						' LEFT JOIN #__md_players AP on (AP.PlayerID = M.MatchAwayPlayerID)'.
						' LEFT JOIN #__md_teams AT on (AT.TeamID = M.MatchAwayTeamID)'.
						' LEFT JOIN #__md_events E on (E.EventID = M.MatchEventID)'.
					' WHERE'.
						' M.MatchEventID LIKE '.$db->Quote( $selectevent ).' AND'.
						' M.MatchSeasonID LIKE '.$db->Quote( $selectseason ).' AND'. 
						' M.MatchVenueID LIKE '.$db->Quote( $selectvenue ).' AND'.
						' M.MatchDate LIKE '.$db->Quote( $selectdate ).  						
					' ORDER BY MatchID';

        return $query;
    }

    public function getData()
    {
    	
        // Lets load the data if it doesn't already exist
        if (empty( $this->_data ))
        {
            $query = $this->_buildQuery();
            $this->_data = $this->_getList( $query, $this->getState('matchdart.matches.limitstart'), $this->getState('matchdart.matches.limit') );
        }
        return $this->_data;
    }
    
    public function getDateformat()
    {
    	if (empty($this->_dateformat))
    	{
			$params = &JComponentHelper::getParams( 'com_matchdart' );
			$this->_dateformat = $params->get('md_formatdate');
    	}
    	return $this->_dateformat;
    }

    public function getPagination()
    {
        if (empty($this->_pagination))
        {
            jimport('joomla.html.pagination');
            $this->_pagination = new JPagination( $this->getTotal(), $this->getState('matchdart.matches.limitstart'), $this->getState('matchdart.matches.limit') );
        }

        return $this->_pagination;
    }

    public function getTotal()
    {
        if (empty($this->_total))
        {
            $query = $this->_buildQuery();
            $this->_total = $this->_getListCount($query);
        }

        return $this->_total;
    }
    
    public function getEventselect()
    {
    	$app = &JFactory::getApplication();

		$context			= 'com_matchdart.matches.list.';
		$showevent		= $app->getUserStateFromRequest( $context.'$eventselect',		'eventselect',		'0',	'cmd' );
    	
    	if (empty($this->_eventselect))
    	{
    	$currentValue = $showevent;
        $query = 'SELECT * FROM #__md_events ORDER BY EventID';
        $events = $this->_getList($query);

        $k=1;
        $option[0] = JHTML::_('select.option', '0', JText::_( 'MD_SELECT_ALL'));
        //FIXME: 'foreach' --> error if events table empty
        foreach ($events as $event){
        	$inactive = ($event->EventPublish == 0) ? 'true' : 'false';
        	$option[$k] = JHTML::_('select.option', $event->EventID, $event->EventName);
        	$k++;
        }
        
        $this->_eventselect = JHTML::_('select.genericlist', $option, 'eventselect', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $currentValue);;
        
    	}
    	return $this->_eventselect;
    }

	public function getSeasonselect()
    {
    	$app = &JFactory::getApplication();

		$context			= 'com_matchdart.matches.list.';
		$showseason		= $app->getUserStateFromRequest( $context.'$seasonselect',	'seasonselect',		'0',	'cmd' );
    	
		if (empty($this->_seasonselect))
    	{
    	$currentValue = $showseason;
        $query = 'SELECT * FROM #__md_seasons ORDER BY SeasonID';
        $seasons = $this->_getList($query);

        $k=1;
        $option[0] = JHTML::_('select.option', '0', JText::_( 'MD_SELECT_ALL'));
        //FIXME: 'foreach' --> error if seasons table empty
        foreach ($seasons as $season){
        	$inactive = ($season->SeasonPublish == 0) ? 'true' : 'false';
        	$option[$k] = JHTML::_('select.option', $season->SeasonID, $season->SeasonName);
        	$k++;
        }
        
        $this->_seasonselect = JHTML::_('select.genericlist', $option, 'seasonselect', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $currentValue);;
        
    	}
    	return $this->_seasonselect;
    }
    
	public function getVenueselect()
    {
    	$app = &JFactory::getApplication();

		$context			= 'com_matchdart.matches.list.';
		$showvenue		= $app->getUserStateFromRequest( $context.'$venueselect',		'venueselect',		'0',	'cmd' );
    	
    	if (empty($this->_venueselect))
    	{
    	$currentValue = $showvenue;
        $query = 'SELECT * FROM #__md_venues ORDER BY VenueID';
        $venues = $this->_getList($query);

        $k=1;
        $option[0] = JHTML::_('select.option', '0', JText::_( 'MD_SELECT_ALL'));
        //FIXME: 'foreach' --> error if venues table empty
        foreach ($venues as $venue){
        	$option[$k] = JHTML::_('select.option', $venue->VenueID, $venue->VenueName);
        	$k++;
        }
        
        $this->_venueselect = JHTML::_('select.genericlist', $option, 'venueselect', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $currentValue);;
        
    	}
    	return $this->_venueselect;
    }

	public function getDateselect()
    {
    	$app = &JFactory::getApplication();

		$context			= 'com_matchdart.matches.list.';
		$showdate		= $app->getUserStateFromRequest( $context.'$dateselect',		'dateselect',		'0',	'cmd' );
    	
    	if (empty($this->_dateselect))
    	{
    	$currentValue = $showdate;
        $query = 'SELECT DISTINCTROW MatchDate FROM #__md_matches ORDER BY MatchDate DESC';
        $dates = $this->_getList($query);

        $k=1;
        $option[0] = JHTML::_('select.option', '0', JText::_( 'MD_SELECT_ALL'));
        //FIXME: 'foreach' --> error if matches table empty
        foreach ($dates as $date){
        	$option[$k] = JHTML::_('select.option', $date->MatchDate, $date->MatchDate);
        	$k++;
        }
        
        $this->_dateselect = JHTML::_('select.genericlist', $option, 'dateselect', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $currentValue);;
        
    	}
    	return $this->_dateselect;
    }
}
?>